package com.gdqy.FCS.web;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.gdqy.FCS.common.api.FastResponse;
import com.gdqy.FCS.common.api.Fileupload;
import com.gdqy.FCS.common.api.SendEmail;
import com.gdqy.FCS.entity.DesignerInfo;
import com.gdqy.FCS.entity.EnterpriseInfo;
import com.gdqy.FCS.entity.ProviderInfo;
import com.gdqy.FCS.entity.Special;
import com.gdqy.FCS.entity.User;
import com.gdqy.FCS.service.CollectionService;
import com.gdqy.FCS.service.DesignerInfoService;
import com.gdqy.FCS.service.EnterpriseInfoService;
import com.gdqy.FCS.service.InformationService;
import com.gdqy.FCS.service.ProviderInfoService;
import com.gdqy.FCS.service.SpecialService;
import com.gdqy.FCS.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private DesignerInfoService designerInfoService;
	@Autowired
	private SpecialService specialService;
	@Autowired
	private ProviderInfoService providerInfoService;
	@Autowired
	private EnterpriseInfoService enterpriseInfoService;
	@Autowired
	private CollectionService collectionService;
	@Autowired
	private InformationService informationService;
	
	private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

	/****************************************************************** 登录登出功能 ******************************************************************************************/
	// 处理页面跳转
	@RequestMapping("deal_login")
	public ModelAndView deal_login() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("common/login");
		return modelAndView;
	}

	@RequestMapping("login")
	public ModelAndView loginSubmit(@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password, HttpSession session) {
		ModelAndView modelAndView = new ModelAndView();
		if (username != "" && username != null && password != "" && password != null) {

			User user = userService.selectByName(username);

			if (user == null) {
				modelAndView.addObject("msg", "用户名或密码错误");
				modelAndView.setViewName("common/login");
			} else {
				// 如果用户的状态是激活
				if (user.getStatus() == 1) {
					// 对数据库中加密 的密码进行比对
					boolean flag = passwordEncoder.matches(password, user.getPassword());
					if (flag) {
						int user_id = user.getId();
						session.setAttribute("user", user);
						session.setAttribute("username", username);
						session.setAttribute("user_id", user_id);
						// 判断角色,并往session中加入对应角色的id
						String role = user.getRole();
						switch (role) {
						case "designer":
							DesignerInfo designerInfo = designerInfoService.selectByUser_id(user_id);
							session.setAttribute("designer_id", designerInfo.getId());
							break;
						case "common":
							// 普通用户
							
							break;
						case "provider":
							// 供应商
							ProviderInfo providerInfo = providerInfoService.selectByUser_id(user_id);
							session.setAttribute("provider_id", providerInfo.getId());
							break;
						case "enterprise":
							// 企业
							EnterpriseInfo enterpriseInfo = enterpriseInfoService.selectByUser_id(user_id);
							session.setAttribute("enterprise_id", enterpriseInfo.getId());
							break;
						case "admin":
							// 管理员
							break;
						default:
							break;
						}

						modelAndView.addObject("user", user);
						modelAndView.setViewName("redirect:/index/index.do");
					} else {
						modelAndView.addObject("msg", "用户名或密码错误");
						modelAndView.setViewName("common/login");
					}
				} else {
					modelAndView.setViewName("common/error");
					modelAndView.addObject("msg", "用户状态未激活或因违反本站相关规定被停用！");
				}

			}
		}
		return modelAndView;
	}

	// 登出
	@RequestMapping("logout")
	public ModelAndView logout(HttpSession session) {
		session.invalidate();
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("index");
		return modelAndView;
	}
	/************************************************************ 普通用户个人中心 **********************************************************************/
	@RequestMapping("user")
	public ModelAndView user(int user_id){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("user/user");
		//获取用户基本信息
		User user = userService.selectById(user_id);
		modelAndView.addObject("user",user);
		//收藏作品数
		int collection_count = collectionService.selectCountByUser_id(user_id);
		modelAndView.addObject("collection_count", collection_count);
		//资讯数
		int information_count = informationService.selectCountByRelease_id(user_id);
		modelAndView.addObject("information_count", information_count);
		return modelAndView;
	}
	//处理修改信息请求
	@RequestMapping("deal_changeInfo")
	public ModelAndView deal_changeInfo(int user_id){
		ModelAndView modelAndView = new ModelAndView();
		//用户信息
		User user = userService.selectById(user_id);
		modelAndView.addObject("user", user);
		modelAndView.setViewName("user/changeInfo");
		return modelAndView;
	}
	//真正修改信息
	@RequestMapping("changeInfo")
	public ModelAndView changeInfo (User user,MultipartFile photo_pic) throws IllegalStateException, IOException{
		//文件原始名
		String originalFilename =  photo_pic.getOriginalFilename();
		//如果头像为空，不做处理,否则 修改
		if(photo_pic != null && originalFilename!=null && originalFilename!="" ){
			Fileupload fileupload = new Fileupload();
			String url=fileupload.upload(photo_pic, "designer", user.getUsername(), "designer-info");
			user.setPhoto_link(url);
			userService.update(user);
		}
	 return new ModelAndView("redirect:/user/deal_changeInfo.do?user_id="+user.getId());
		
	}
	/****************************************************************** 注册功能 ******************************************************************************************/

	@RequestMapping("deal_register")
	public ModelAndView deal_register() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("common/register");
		return modelAndView;
	}

	@RequestMapping("register")
	public @ResponseBody Object registerSubmit(User user) {

		String msg = "";
		if (user != null) {
			user.setReg_datetime(new Date());
			String password = user.getPassword();
			// 加密密码
			user.setPassword(passwordEncoder.encode(password));
			user.setStatus(0);
			user.setValidate_code(UUID.randomUUID().toString());
			user.setValidate_time(new Date());
			userService.insert(user);
			String email = user.getEmail();
			StringBuffer sb = new StringBuffer("点击下面链接激活账号，48小时内有效，否则需要重新注册账号，链接只能使用一次，请尽快激活！</br>");
			sb.append("<a href=\"http://localhost:8080/FCS/user/validateEmail.do?email=");
			sb.append(email);
			sb.append("&validateCode=");
			// 加密验证码
			sb.append(passwordEncoder.encode(user.getValidate_code()));
			sb.append("\">http://localhost:8080/FCS/user/validateEmail.do?email=");
			sb.append(email);
			sb.append("&validateCode=");
			sb.append(passwordEncoder.encode(user.getValidate_code()));
			sb.append("</a>");
			SendEmail.send(email, sb.toString());
			System.out.println("发送邮件");
			msg = "注册成功,请尽快到邮箱里面点击链接激活账号";
		} else {
			msg = "注册失败";
		}

		return FastResponse._().obj(msg);

	}

	// 验证邮箱 激活用户
	@RequestMapping("validateEmail")
	public ModelAndView validateEmail(@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "validateCode", required = true) String validateCode) {

		ModelAndView modelAndView = new ModelAndView();
		String msg = "";

		// 通过邮箱找用户
		User user = userService.selectByEmail(email);

		if (user != null) {

			// 验证用户激活状态
			if (user.getStatus() == 0) {
				Date current_time = new Date();
				Date validate_time = user.getValidate_time();
				// 将日期转换成时间戳
				long dif = current_time.getTime() - validate_time.getTime();

				// 验证时间是否超过48小时
				if (dif / (60 * 60 * 1000) > 48) {
					// 验证超时，删除用户信息，重新注册
					msg = "已超过验证时间，用户名与邮箱均已失效，请重新注册";
					userService.delete(user);
					modelAndView.setViewName("error/error");
				} else {
					// 验证码是否正确
					Boolean validate = passwordEncoder.matches(user.getValidate_code(), validateCode);
					if (validate) {

						int user_id = user.getId();
						String phone = user.getPhone();

						// 判断角色
						String role = user.getRole();
						switch (role) {
						case "designer":
							// 设计师表录入数据
							DesignerInfo designerInfo = new DesignerInfo();
							designerInfo.setUpdate_time(new Date());
							designerInfo.setUser_id(user_id);
							designerInfo.setPhone(phone);
							designerInfoService.insert(designerInfo);
							// 建立默认专辑
							Special special = new Special();
							special.setDesigner_id(designerInfo.getId());
							special.setName("默认专辑");
							specialService.insert(special);
							// 并更新用户的激活状态，为已激活
							user.setStatus(1);
							userService.update(user);
							break;
						case "common":
							/* 普通用户信息已经录入，此处不用录入 */
							break;
						case "provider":
							// 供应商表录入信息
							ProviderInfo providerInfo = new ProviderInfo();
							providerInfo.setUpdate_time(new Date());
							providerInfo.setUser_id(user_id);
							providerInfo.setPhone(phone);
							providerInfo.setPopularity(0);
							// 数据库录入数据
							providerInfoService.insert(providerInfo);
							// 并更新用户的激活状态，为已激活
							user.setStatus(1);
							userService.update(user);
							break;
						case "enterprise":
							// 企业表录入数据
							EnterpriseInfo enterpriseInfo = new EnterpriseInfo();
							enterpriseInfo.setUser_id(user_id);
							enterpriseInfo.setPhone(phone);
							enterpriseInfo.setPopularity(0);
							enterpriseInfo.setUpdate_time(new Date());
							// 数据库录入数据
							enterpriseInfoService.insert(enterpriseInfo);
							// 并更新用户的激活状态，为已激活
							user.setStatus(1);
							userService.update(user);
							break;
						case "admin":
							// 管理员--貌似也不用关联其他表去录入
							// 并更新用户的激活状态，为已激活
							user.setStatus(1);
							userService.update(user);
							break;

						default:
							break;
						}
						msg = "激活成功，赶紧登录吧！";

						modelAndView.setViewName("common/login");
					} else {
						msg = "验证失败!";
						modelAndView.setViewName("error/error");
					}
				}

			} else {
				msg = "该账户已经激活!请勿重复提交！";
				modelAndView.setViewName("error/error");
			}
		}
		modelAndView.addObject("msg", msg);
		return modelAndView;
	}

	/************************************************************ 前端验证 **********************************************************************/

	// 前端ajax请求时，看看数据库里面有没有该用户名
	@RequestMapping("verifyUsername")
	public @ResponseBody String verifyUsername(@RequestParam(value = "username", required = true) String username) {
		User user = userService.selectByName(username);
		if (user == null) {
			return "success";
		}
		return "fail";
	}

	// 前端ajax请求时，看看数据库里面有没有该邮箱
	@RequestMapping("verifyEmail")
	public @ResponseBody String verifyEmail(@RequestParam(value = "email", required = true) String email) {
		User user = userService.selectByEmail(email);
		if (user != null) {
			return "fail";
		}
		return "success";
	}

	/************************************************************ 密码修改 **********************************************************************/
	// 处理页面跳转
	@RequestMapping("deal_changePSW")
	public String deal_changePSW() {
		return "common/changePassword";
	}

	@RequestMapping("updatePassword")
	public ModelAndView updatePassword(int id, String newPSW, String oldPassword) {
		ModelAndView modelAndView = new ModelAndView();
		String msg = "";
		User user = userService.selectById(id);
		if (user != null) {
			if (passwordEncoder.matches(oldPassword, user.getPassword())) {
				user.setPassword(passwordEncoder.encode(newPSW));
				userService.update(user);
				msg = "密码修改成功，以后登录记得用新密码哦";
			} else {
				msg = "原密码错误，请检查后重新提交";
			}

		} else {
			msg = "密码修改失败，请稍后重试";
		}
		modelAndView.addObject("msg", msg);
		modelAndView.setViewName("common/changePassword");
		return modelAndView;
	}

	/************************************************************ 忘记密码 **********************************************************************/
	@RequestMapping("forgetPassword")
	public @ResponseBody Object forgetPassword(String email) {
		User user = userService.selectByEmail(email);
		String msg = "";
		if (user != null) {
			// 获取系统当前时间
			Date current_time = new Date();
			long dif = current_time.getTime() - user.getValidate_time().getTime();
			// 大于5分钟 可重新发送邮件
			if (dif / (60 * 1000) > 5) {
				user.setValidate_code(UUID.randomUUID().toString());
				user.setValidate_time(new Date());
				userService.update(user);
				StringBuffer sb = new StringBuffer("点击下面链接修改密码，5分钟内有效，否则重新注册账号，链接只能使用一次，请尽快激活！</br>");
				sb.append("<a href=\"http://localhost:8080/FCS/user/fogetPasswordView.do?email=");
				sb.append(email);
				sb.append("&validateCode=");
				// 加密验证码
				sb.append(passwordEncoder.encode(user.getValidate_code()));
				sb.append("\">http://localhost:8080/FCS/user/fogetPasswordView.do?email=");
				sb.append(email);
				sb.append("&validateCode=");
				sb.append(passwordEncoder.encode(user.getValidate_code()));
				sb.append("</a>");
				SendEmail.send(email, sb.toString());
				msg = "邮件已经发送到对应的邮箱里，请注意及时更改密码！";
			} else {
				msg = "邮件已经发送过了，请勿重复提交";
			}

		} else {
			msg = "该邮箱不存在，请检查后重新提交";
		}

		return FastResponse._().obj(msg);
	}

	//
	@RequestMapping("fogetPasswordView")
	public ModelAndView fogetPasswordView(@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "validateCode", required = true) String validateCode) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("fogetPassword");
		modelAndView.addObject("email", email);
		modelAndView.addObject("validateCode", validateCode);
		return modelAndView;
	}

	@RequestMapping("handleForgetPassword")
	public ModelAndView handleForgetPassword(@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "validateCode", required = true) String validateCode,
			@RequestParam(value = "newPassword", required = true) String newPassword) {
		ModelAndView modelAndView = new ModelAndView();
		String msg = "";
		User user = userService.selectByEmail(email);

		if (user != null) {
			if (passwordEncoder.matches(user.getValidate_code(), validateCode)) {
				Date current_time = new Date();
				Date validate_time = user.getValidate_time();
				// 将日期转换成时间戳
				long dif = current_time.getTime() - validate_time.getTime();
				// 验证时间是否超过48小时
				if (dif / (60 * 1000) > 5) {
					// 验证超时，删除用户信息，重新注册
					msg = "已超过验证时间，用户名与邮箱均已失效，请重新注册";
					userService.delete(user);
					modelAndView.setViewName("registerError");
				} else {
					user.setPassword(passwordEncoder.encode(newPassword));
					// 使用完将验证码设置为空
					user.setValidate_code(null);
					userService.update(user);
					msg = "密码修改成功";
					modelAndView.setViewName("common/login");
				}
			} else {
				msg = "验证失败，请稍后重试";
			}
		}
		modelAndView.addObject("msg", msg);
		return modelAndView;

	}
	
	
}
